// 创建右键菜单
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'downloadAllImages',
    title: '下载所有图片',
    contexts: ['all']
  });

  chrome.contextMenus.create({
    id: 'downloadAllVideos',
    title: '下载所有视频',
    contexts: ['all']
  });

  chrome.contextMenus.create({
    id: 'downloadAllAudios',
    title: '下载所有音频',
    contexts: ['all']
  });
});

// 处理右键菜单点击事件
chrome.contextMenus.onClicked.addListener((info, tab) => {
  // 向content script发送消息获取资源
  chrome.tabs.sendMessage(tab.id, { action: 'getResources' }, (response) => {
    if (!response) return;

    let resources = [];
    switch (info.menuItemId) {
      case 'downloadAllImages':
        resources = response.images;
        break;
      case 'downloadAllVideos':
        resources = response.videos;
        break;
      case 'downloadAllAudios':
        resources = response.audios;
        break;
    }

    // 下载所有资源
    resources.forEach(resource => {
      if (resource.url) {
        chrome.downloads.download({
          url: resource.url,
          filename: getFilenameFromUrl(resource.url)
        });
      }
    });
  });
});

// 从URL中获取文件名
function getFilenameFromUrl(url) {
  try {
    const urlObj = new URL(url);
    const pathname = urlObj.pathname;
    const filename = pathname.substring(pathname.lastIndexOf('/') + 1);
    return filename || 'download';
  } catch (e) {
    return 'download';
  }
}